<?php
// +----------------------------------------------------------------------
// | 阿里云短信
// +----------------------------------------------------------------------
// | Author: myh
// +----------------------------------------------------------------------
namespace app\common\lib\msg;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use think\facade\Log;

class AliYunMessage implements Message
{
    
    public function send($mobile, $code){
        
        $config = new Config([
            "accessKeyId" => config('aliyun.accessKeyId'),
            "accessKeySecret" => config('aliyun.accessKeySecret')
        ]);
        $config->endpoint = config('aliyun.dysmsapi');
        $client = new Dysmsapi($config);

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $mobile,
            "signName" => config('aliyun.signName'),
            "templateCode" => config('aliyun.templateCode'),
            "templateParam" => json_encode(['code'=>$code])
        ]);

        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $rs = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            Log::write("获取手机验证码：".json_encode($rs));
            return true;
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            Log::write('获取手机验证码异常：'.$error->message);
            return false;
        }
    }
}